﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Gmantis.Controls.DataGrid
{
    public class DataGridLengthTypeConverter : TypeConverter
    {
        // Methods
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType.FullName == "System.String");
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            double num2;
            string s = value as string;
            if (s == null)
            {
                return null;
            }
            s = s.Trim();
            switch (s)
            {
                case "Auto":
                    return DataGridLength.Auto;

                case "AutoStar":
                case "Auto*":
                    return new DataGridLength(1.0, DataGridUnitType.AutoStar);
            }
            DataGridUnitType pixel = DataGridUnitType.Pixel;
            int index = s.IndexOf("*");
            if (index >= 0)
            {
                pixel = DataGridUnitType.Star;
                s = s.Substring(0, index);
            }
            if (s.EndsWith("px"))
            {
                s = s.Substring(0, s.Length - 2);
            }
            if (!double.TryParse(s, NumberStyles.Any, (IFormatProvider)CultureInfo.InvariantCulture.NumberFormat, out num2))
            {
                num2 = 1.0;
            }
            return new DataGridLength(num2, pixel);
        }
    }
}
